﻿<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加报价单据</title>
    <link rel="stylesheet" href="../css/from.css">
    <link rel="stylesheet" href="../themes/default/easyui.css">
    <link rel="stylesheet" href="../themes/icon.css">
    <script src="../js/jquery.min.js"></script>
    <script src="../js/jquery.easyui.min.js"></script>
    <script src="../js/easyui-lang-zh_CN.js"></script>
    <script>
        function loadSupplier() {
           $("#list").dialog({
                title: '供应商列表',
                width: 905,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
           });
        }
        
        function loadPart() {
        	var customName=$("#customName").textbox('getText');
        	if(customName==null||customName==""){
        		alert("请选择客户！");
        		return false;
        	}
		    $("#partList").dialog({
		        title: '选择配件',
		        width: 1000,
		        height: 400,
		        closed: false,
		        cache: false,
		        modal: true,
		   });
		}
        function closeDg(name) {
            $("#customName").val(name);
            $("#list").dialog("close");
        }
        //用于将子页面的数据绑定到相关元素上
        function bindValue(data){
        	var name=data[0];
        	var linkman=data[1];
        	var phone=data[2];
        	var fax=data[3];
        	$('#customName').textbox('setText',name);	
        	$('#linkman').textbox('setText',linkman);	
        	$('#phone').textbox('setText',phone);	
        	$('#fax').textbox('setText',fax);	
        }
        
        function closeSupplier(){
        	//$("#list").dialog("close");
        
        	$("#list").dialog("destroy");
        	$("#absolute").html("<div id='list'  style='display: none' data-options='onClose:function(){closeSupplier()}'>"+
        	"<iframe src='supplier_list.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        
        function myformatter(date){
          var y=date.getFullYear();
          var m=date.getMonth()+1;
          var d=date.getDate();
          var hour=date.getHours();
          var mini=date.getMinutes();
          var sec=date.getSeconds();
          return y+"-"+(m<10?('0'+m):m)+"-"+(d<10?('0'+d):d)+" "+(hour<10?('0'+hour):hour)+":"+(mini<10?('0'+mini):mini)+":"+(sec<10?('0'+sec):sec);
        }
        function myformatter2(date){
        	var y = date.getFullYear();
        	var m = date.getMonth()+1;
        	var d = date.getDate();
        	return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
        }
        
        function closePart() {
            $("#partList").dialog("destroy");
        	$("#part_List_parent").html("<div id='partList'  style='display: none' data-options='onClose:function(){closePart()}'>"+
        	"<iframe src='addPart.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        
        function addToPage(row){
        	var oldRow=$('#selected_part').datagrid('getRows');
        	if(oldRow.length>0){
				$('#selected_part').datagrid('deleteRow',oldRow.length-1); 
        	}
            $('#selected_part').datagrid('appendRow',{
				code: row.code,
				partName: row.partName,
				partBrand: row.partBrand,
				partNo: row.partNo,
				amount: 1,
				sellPrice: row.sellPrice,
				price: row.sellPrice,
				cycle:myformatter2(new Date()),
				memo: ''
		    });
		    $("#selected_part").datagrid('appendRow',{
				'partBrand':"合计",
				'amount':total('amount'),
				'price':total('price')
            });
        }
        
        
        
        function total(col){
        	var rows=$("#selected_part").datagrid('getRows');
        	var total_amount=0;
        	for(var i=0;i<rows.length;i++){
        		total_amount+=parseFloat(rows[i][col]);
        	}
        	return total_amount;
          }
        
         function addpart(row){
            var oldRow=$('#selected_part').datagrid('getRows');
            if(oldRow!=null&&oldRow!=''){
	            for(var i=0;i<row.length;i++){
	                for(var j=0;j<oldRow.length;j++){
	                   if(oldRow[j]['code']==row[i]['code']){
	         		       alert("不能添加重复配件");
	         		      return false;
	         		   }
	                }
                }
                for(var i=0;i<row.length;i++){
	             	addToPage(row[i]);
                }
             }else{
             	for(var i=0;i<row.length;i++){
	             	addToPage(row[i]);
                }
             }
             closePart();
         }
          function change_amount_sellPrice(input_index,input){
         	var amount=$(input).parent().parent().parent().find('[name="amount"]').val();
         	var sellPrice=$(input).parent().parent().parent().find('[name="sellPrice"]').val();
         	var price=parseFloat(amount)*parseFloat(sellPrice);
         	$('#selected_part').datagrid('updateRow',{
				index: input_index,
				row: {
					amount: amount,
					sellPrice:sellPrice,
					price: price
				}
			});
			var oldRow=$('#selected_part').datagrid('getRows');
			$('#selected_part').datagrid('deleteRow',oldRow.length-1); 
			$("#selected_part").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
           	});
         }
         
         function change_date_memo(input_index,input){
         	var cycle=$(input).parent().parent().parent().find('[name="cycle"]').val();
         	var memo=$(input).parent().parent().parent().find('[name="memo"]').val();
         	$('#selected_part').datagrid('updateRow',{
				index: input_index,
				row: {
					cycle: cycle,
					memo: memo
				}
			});
         }
         
         function test(){
         }
         
		function save_fun(){
			var result_temp=false;
			
			var allData=$('#selected_part').datagrid('getRows');
			if(allData.length<1){
				alert("请添加配件");
				return ;
			}
			var code = $("#code").textbox('getText');
			var customName = $("#customName").textbox('getText');
			if(customName==""){
				alert("请选择供应商。");
				return ;
			}
			var linkman = $("#linkman").textbox('getText');
			var phone = $("#phone").textbox('getText');
			var offerTime = $("#addDate").textbox('getText');
			var money=	allData[allData.length-1].price;
			var memo = $("#memo").val();
			var total = JSON.stringify($('#selected_part').datagrid('getData').total - 1);
	
			 $.ajax({
			 	cache:false,
				async:false,
				type : "post",//请求类型
				url:'/kxmanage/offerPriceBill/saveOfferBill',
				data : {
					'code' : code,
					'customName' : customName,
					'linkman' : linkman,
					'phone' : phone,
					'offerTime':offerTime,
					'memo' : memo,
					'money' : money,
					'data' : JSON.stringify(allData),
					'total' : total
				},
				dataType : "json",//ajax接口（请求url）返回的数据类型
				success : function(data) {//data：返回数据（json对象）
					if(data.result=="success"){
						result_temp=true;
					}else{
						result_temp=false;
					}
				}
			});
			
			return result_temp;
		}
         
         
         
         function deleteRow(index){
         	//删除当前行
         	$('#selected_part').datagrid('deleteRow',index);
         	//拿到之前的数据并重新封装，刷新index
         	var oldData=$('#selected_part').datagrid('getData');
         	$('#selected_part').datagrid('loadData',oldData);
         	//更新最后一行
         	var oldRow=$('#selected_part').datagrid('getRows');
         	$('#selected_part').datagrid('deleteRow',oldRow.length-1); 
			$("#selected_part").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
           	});
         }
		
		function closeTabs(){
			parent.closeTabs("添加报价单据");
		}
        function clearPartDatagrid(){}
        
        
		$(function(){
			$("#save").click(function() {
				if(save_fun()){
					alert("添加成功!");
					parent.addTabs("报价单据管理","goods/quotationDocumentManagement.jsp");
					closeTabs();
				}else{
					alert("未知错误!");
				}
			});
		
        	$.ajax({
    			url:'/kxmanage/makecode/makeNewCode',
    			data:{prefix:'BJ'},
    			dataType:'json',
    			type:'post',
    			success:function(data){
    				$('#code').textbox('setText',data.result);	
    			}
    		});
    		//绑定报价日期。
			var curr_time = new Date();
			$("#addDate").datetimebox("setValue",myformatter(curr_time));
			
			//加载转中配件的数据表格
			$("#selected_part").datagrid({
				checkOnSelect:false,
				rownumbers:true,
			    columns:[[
                    {field:'code',title:'配件编号',width:130},
                    {field:'partName',title:'配件名称',width:180},
                    {field:'partBrand',title:'配件品牌',width:120},
                    {field:'partNo',title:'配件型号',width:100},
                    {field:'amount',title:'数量',width:100,editor:'numberbox',
                    	formatter:function(value,row,index){
	                        if(row.sellPrice==null){
	                    		return value;
	                    	}
                            return '<input name="amount" onchange="change_amount_sellPrice('+index+',this)" type="number" value="'+value+'" style="width:30px;"/>';
                        }
                    },
                    {field:'sellPrice',title:'单价',width:100, 
                        formatter:function(value,row,index){
	                        if(row.sellPrice==null){
	                    		return null;
	                    	}
                            return '<input name="sellPrice" onchange="change_amount_sellPrice('+index+',this)" type="number" value="'+value+'" style="width:50px;"/>';
                        }
                    },
                    {field:'price',title:'金额',width:100,
                         formatter:function(value,row,index){
                         	if(row.sellPrice==null){
	                    		return "￥"+value;
	                    	}
                            return "￥"+value;
                        }
                    },
                    {field:'cycle',title:'交货期',width:150,formatter:function(value,row,index){
                    	if(row.sellPrice==null){
                    		return null;
                    	}
                    	
                    	return '<input type="date" onchange="change_date_memo('+index+',this)" name="cycle" value="'+value+'" maxlength="30" class="easyui-datebox" style="height:20px"/>';
                    }},
                    {field:'memo',title:'备注',width:190,formatter:function(value,row,index){
                    	if(row.sellPrice==null){
                    		return null;
                    	}
                    	return '<input type="text" onchange="change_date_memo('+index+',this)" name="memo" value="'+value+'" style="width:100px;"/>';
                    }},
                    {field:'opt',title:'操作',width:100,formatter:function (value,row,index) {
                        if(row.sellPrice==null){
                    		return null;
                    	}
                            var context="<a href=\"javascript:deleteRow("+index+")\">删除</a>&nbsp;&nbsp;";
                            return context;
                        }}

                ]],
			    toolbar:'#wu_toolbar',
			    onClickRow: function(index, data) {
			        $(this).datagrid('unselectRow', index);
			    }
			});
        });
        
        function audit(){
			if(save_fun()){
	         	var code = $("#code").textbox('getText');
	         	$.ajax({
	         		url:'/kxmanage/offerPriceBill/audit',
	         		data:{code:code},
	         		dataType:'json',
	         		type:'post',
	         		success:function(data){
	         			if(data.result="success"){
	         				alert("添加成功!");
							parent.addTabs("报价单据管理","goods/quotationDocumentManagement.jsp");
							closeTabs();
	         			}else{
	         				alert("审核失败！");
	         			}
	         		}
	         	});
			}else{
				alert("添加失败！");
			}         
         	
         }
        
    </script>
    <style>
        body {
            font-size:12px;
            padding:10px
        }
        .l-table-edit {
     	   border-collapse:collapse;border-spacing:0;
        }
        .l-table-edit-td {
            padding:4px;
            font-size:12px;
            border: #84a0c4 1px solid;
        }
        
        input[type='text']{
        	height:20px !important;
        }
        
    </style>


</head>
<body>
<form name="form"  id="form" action="" method="post">
    <table cellpadding="0" cellspacing="0" class="l-table-edit" style="width:100%"  >
        <tr >
            <td width="17%"  align="right" class="l-table-edit-td">报价编号：</td>
            <td width="27%" align="left" class="l-table-edit-td">
            	<input  type="text" readonly="readonly" class="easyui-textbox" id="code" value="" size="30" style="height:20px" maxlength="100" ltype="text" />
            </td>
            <td width="13%"  align="right" class="l-table-edit-td">报价日期：</td>
            <td width="43%" align="left" class="l-table-edit-td">
            	<input  type="text" id="addDate"  name="orderTime" value="" maxlength="30" class="easyui-datetimebox" style="height:20px"/>
            	<!-- <input  type="text" id="addDate" value="" maxlength="30" class="easyui-datetimebox" style="height:20px"/> -->
            </td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">
                <a href="javascript:loadSupplier()">客户名称：</a>
            </td>
            <td  width="27%"align="left" class="l-table-edit-td">
                <input class="easyui-textbox" type="text" id="customName"  value="" size="30" maxlength="100" ltype="text"  />
            <td width="13%" align="right" class="l-table-edit-td">联系人员：</td>
            <td width="43%"align="left" class="l-table-edit-td">
                <input class="easyui-textbox" name="" type="text" id="linkman" value="" maxlength="30" ltype="text" /></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">电话：</td>
            <td width="27%" align="left" class="l-table-edit-td"><input class="easyui-textbox" type="text" id="phone" value="" size="30" maxlength="50" ltype="text" /></td>
            <td width="13%" align="right" class="l-table-edit-td">传真：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input class="easyui-textbox" type="text"  class="l-table-edit" id="fax" value="" maxlength="50"  ltype="text" /></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td" valign="top">备注：</td>
            <td align="left" class="l-table-edit-td" colspan="3">
                <input id="memo" class="l-table-edit easyui-textbox" style="width: 634px;"></input>
            </td>
        </tr>
    </table>
</form>
<br>
<div id="buttons" style="margin-bottom: 10px;">
	<input  type="button" value="新   增" style="width:60px">
	<a href="javascript:loadPart()"><input  type="button" value="添加配件" style="width:60px"></a>
	<input  type="button" id="save" value="保   存" style="width:60px">
	<input onclick="audit()" type="button" id="check_btn" value="审   核" style="width:60px">
	<input  type="button" value="撤   销" disabled style="width:60px">
	<input onclick="test()"  type="button" value="打   印" style="width:60px">
	<input  type="button" value="生成word" style="width:60px">
	<input  type="button" value="生成订单" disabled style="width:60px">
	<input onclick="closeTabs()" type="button" value="关   闭" style="width:60px">
</div>


<div id="absolute">
	<div id='list'  style='display: none' data-options="onClose:function(){closeSupplier()}">
    	<iframe src='supplier_list.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
	</div>
</div>

<div id="part_List_parent">
<div id="partList"  style="display: none"  data-options='onClose:function(){closePart()}'>
    <iframe src='addPart.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
</div>
</div>

<div id="selected_part" class="easyui-datagrid">

</div>
</body>
</html>